/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.netease.nim.demo.main.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.netease.nim.demo.contact.cache.TeamDataCache;
import com.netease.nim.demo.main.adapter.ContactsAdapter;
import com.netease.nim.demo.main.model.MainTab;
import com.netease.nim.demo.session.activity.P2PMessageActivity;
import com.netease.nim.demo.session.activity.TeamMessageActivity;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.team.TeamService;
import com.netease.nimlib.sdk.team.model.Team;
import com.shwread.android.qysw10000243.R;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import logic.bean.ContactInfo;
import logic.constants.Const;
import logic.util.Utils;


/**
 * @Project： qysw_1.0.8_dev
 * @Title：ContactsFragment
 * @Description：通讯录
 * @Author：wayne
 * @Date：2015年5月25日下午4:32:50
 */
public class ContactsFragment
        extends
        MainTabFragment {
    /**
     * 页面类型   : 1为客户经理，2为普通用户
     */
    private int pageType = 1;
    private ListView contactsListView;
    private List<Object> items;
    private ContactsAdapter mAdapter;
    private View emptyBg;

    private View notifyBar;

    private boolean msgLoaded = false;
    private boolean isMangerLoadOk = true;
    private boolean isTeamLoadOk = false;
    public static int currentPosition;

    public ContactsFragment() {
        setFragmentId(MainTab.CONTACT.fragmentId);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        onCurrent();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        registerObservers(false);
    }

    @Override
    protected void onInit() {
        getPageType();
        findView();
        getContactsList();
        initContactsList();

        registerObservers(true);
    }

    private void registerObservers(boolean register) {
        registerTeamUpdateObserver(register);
    }

    /**
     * 注册群信息&群成员更新监听
     */
    private void registerTeamUpdateObserver(boolean register) {
        if (register) {
            TeamDataCache.getInstance().registerTeamDataChangedObserver(teamDataChangedObserver);
        } else {
            TeamDataCache.getInstance().unregisterTeamDataChangedObserver(teamDataChangedObserver);
        }
    }

    TeamDataCache.TeamDataChangedObserver teamDataChangedObserver = new TeamDataCache.TeamDataChangedObserver() {

        @Override
        public void onUpdateTeams(List<Team> teams) {
        }

        @Override
        public void onRemoveTeam(Team team) {
            //TODO  解散群
            for (Object item : items) {
                if (item instanceof Team) {
                    Team temp = (Team) item;
                    if (TextUtils.equals(temp.getId(), team.getId())) {
                        items.remove(item);
                        mAdapter.notifyDataSetChanged();
                        break;
                    }
                }
            }
        }
    };

    /**
     * 加载群列表
     */
    private void getContactsList() {
        if (pageType == 0) {
            return;
        } else if (pageType == 1) {
            requestContacts(false);
        } else if (pageType == 2) {
            if (null == Const.contactInfo) getUserManger();
            requestContacts(false);
        }

    }

    private void getPageType() {
        if (Const.UserRole.equals("0")) {
            pageType = 0;
        } else if (Const.UserRole.equals("1")) {
            pageType = 1;
        } else if (Const.UserRole.equals("2")) {
            pageType = 2;
        }
    }

    private void notifyDataSetChanged() {

        boolean empty = items.isEmpty();
        emptyBg.setVisibility(empty ? View.VISIBLE : View.GONE);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 跳转到聊天页面
     *
     * @param item
     */
    protected void talkto(Object item) {
        if (item instanceof ContactInfo) {
            ContactInfo info = (ContactInfo) item;
            String str;
            if (Utils.isEmpty(info.getNickName())) {
                str = info.getAccount();
            } else {
                str = info.getNickName();
            }
//			Intent intent = new Intent();
//			intent.putExtra(DefaultConsts.TO_P2P_PAGE_TAG, DefaultConsts.TO_P2P_PAGE_FROM_CONTACT_MANGER);
//			intent.putExtra(DefaultConsts.TO_P2P_PAGE_INFO, str);
//			P2PMessageActivity.start(getActivity(), info.getAccId(), intent);
            P2PMessageActivity.start(getActivity(), info.getAccId(), str);
            //			startActivity(new Intent(getActivity(), P2PMessageActivity.class));
        } else if (item instanceof Team) {
            Team team = (Team) item;
            TeamMessageActivity.start(getActivity(), team.getId());
        }

    }

    /**
     * 获取客户的客户经理信息
     */
    private void getUserManger() {
        NewActionHelp.qryMyBoss(getActivity(), new GetUserMangerHandler());
    }

    private void findView() {
        contactsListView = (ListView) this.getView().findViewById(R.id.new_i_contacts_lv);
        notifyBar = this.getView().findViewById(R.id.status_notify_bar);
        emptyBg = this.getView().findViewById(R.id.new_i_contacts_empty_rlay);
        notifyBar.setVisibility(View.GONE);
    }

    private void initContactsList() {
        items = new ArrayList<Object>();

        mAdapter = new ContactsAdapter(getActivity(), items);
        contactsListView.setAdapter(mAdapter);
        contactsListView.setItemsCanFocus(true);
        contactsListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentPosition = position;
                Object obj = parent.getAdapter().getItem(position);
                talkto(obj);
            }
        });

    }

    private void requestContacts(boolean delay) {

        getHandler().postDelayed(new Runnable() {

            @Override
            public void run() {
                NIMClient.getService(TeamService.class).queryTeamList().setCallback(new RequestCallback<List<Team>>() {

                    @Override
                    public void onException(Throwable arg0) {
                        Logger.e(arg0);
                        isTeamLoadOk = false;
                    }

                    @Override
                    public void onFailed(int arg0) {
                        Logger.i("failed");
                        isTeamLoadOk = true;
                    }

                    @Override
                    public void onSuccess(List<Team> arg0) {
                        Logger.d("success");
                        isTeamLoadOk = true;
                        items.clear();
                        if (arg0 != null) {
                            items.addAll(arg0);
                            if (null != Const.contactInfo) items.add(0, Const.contactInfo);
                        }
                        notifyDataSetChanged();
//						if (pageType == 2 && isMangerLoadOk)
//						{
//						}
//						else if (pageType == 1)
//						{
//							notifyDataSetChanged();
//						}
                    }
                });
            }
        }, delay ? 250 : 0);

    }

    class GetUserMangerHandler
            extends
            ObjectHttpResponseHandler<ContactInfo> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            isMangerLoadOk = false;
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, ContactInfo object, String responseString) {
            isMangerLoadOk = true;
            if (object != null) {
                items.add(0, object);
                Const.contactInfo = object;
                if (isTeamLoadOk) notifyDataSetChanged();
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<ContactInfo>() {
            }.getType();
        }

    }

    @Override
    protected void updateList() {
//		requestContacts(false);
        if (items.size() > 0) items.clear();
        getContactsList();
    }
}
